// 视频card和图片card基本逻辑一致，就是里面放的东西不太一样。一个有preview一个没有

import videoLoadingPng from '@/assets/imgs/YmUpload-videoLoading.png';
import { DeleteOutlined, EyeOutlined, RedoOutlined } from '@ant-design/icons';
import { Button, Divider, Image, Progress, Space } from 'antd';
import { ReactNode, useState } from 'react';
import { getVideoCoverImage } from '../utils';
import { ItemRenderProps } from './interface';
const VIDOEXTENSIONS = [
  'mp4',
  'webm',
  'ogg',
  'mov',
  'avi',
  'wmv',
  'flv',
  '3gp',
];

function ImageDoneRender({
  file,
  preview,
  remove,
  showActionText,
  fileList,
  itemRenderSzie,
}: ItemRenderProps) {
  const [visible, setVisible] = useState(false);
  const [finalUrl, setFinalUrl] = useState<string>(videoLoadingPng);
  const [previewCurrIndex, setPreviewCurrIndex] = useState<number>(0);

  const src = file.thumbUrl || file.url; //thumbUrl base64位码
  if (!src) {
    return null;
  }

  const srcs = (fileList ?? [])
    .map((fileItem) => fileItem.thumbUrl || fileItem.url)
    .filter((item) => item);
  if (!srcs.length) {
    return null;
  }
  let ifVideoFile = false;
  const type = file.type?.split('/')[0];
  if (type && type === 'video') {
    ifVideoFile = true;
  } else if (!type) {
    //编辑时
    const tempUrl = file.url || file.response;
    const extension = tempUrl && tempUrl.split('.').pop().toLowerCase();
    if (VIDOEXTENSIONS.includes(extension)) {
      ifVideoFile = true;
    }
  }

  if (ifVideoFile) {
    getVideoCoverImage(src, itemRenderSzie).then((coverImgsSrc) => {
      setFinalUrl(coverImgsSrc);
    });
  }

  return (
    <>
      <Image.PreviewGroup
        items={srcs as string[]}
        preview={{
          visible,
          current: previewCurrIndex,
          onVisibleChange(value) {
            if (value === false) {
              setVisible(value);
            }
          },
          imageRender: (originalNode, info) => {
            // console.log('--originalNode--info--:', originalNode, info);
            const tempSrc = originalNode.props.src;
            const isVideo =
              tempSrc &&
              (tempSrc.includes('data:video') ||
                VIDOEXTENSIONS.includes(tempSrc.split('.').pop().toLowerCase()))
                ? true
                : false;
            return isVideo ? (
              <video muted width="100%" height="80%" controls src={tempSrc} />
            ) : (
              originalNode
            );
          },
          toolbarRender: (originalNode, info) => {
            const tempFile = fileList[info.current];
            const tempSrc = tempFile.url || tempFile.response;
            const isVideo =
              tempFile.type?.split('/')[0] === 'video' ||
              VIDOEXTENSIONS.includes(tempSrc.split('.').pop().toLowerCase())
                ? true
                : false;
            return isVideo ? null : originalNode;
          },
          onChange: (current: number, prevCurrent: number) => {
            //切换预览图
            // console.log('--切换--current--prevCurrent--:', current, prevCurrent);
            setPreviewCurrIndex(current);
          },
        }}
      >
        <Image
          src={ifVideoFile ? finalUrl : src}
          alt={file.name}
          preview={{
            mask: false,
          }}
        />
      </Image.PreviewGroup>

      <span className="ant-upload-list-item-actionslist">
        <span
          className="action-tabs"
          onClick={() => {
            // console.log('--file--fileList--:', file, fileList)
            const fileIndex = fileList.findIndex((fileItem) => {
              const { uid, url, name, response } = fileItem;
              let res = false;
              if (uid && file.uid) {
                res = uid === file.uid ? true : false;
              } else if (url && file.url) {
                res = url === file.url ? true : false;
              } else if (name && file.name) {
                res = name === file.name ? true : false;
              } else if (
                typeof response === 'string' &&
                typeof file.response === 'string' &&
                response &&
                file.response
              ) {
                res = response === file.response ? true : false;
              }

              return res;
            });
            setPreviewCurrIndex(fileIndex ?? 0);
            setVisible(true);
            preview(); //是为了触发YmUpload.onPreview()
          }}
        >
          <EyeOutlined className="action-icon" />
          {showActionText ? '预览' : null}
        </span>
        <Divider type="vertical" style={{ backgroundColor: '#fff' }}></Divider>
        <span className="action-tabs" onClick={remove}>
          <DeleteOutlined className="action-icon" />
          {showActionText ? '删除' : null}
        </span>
      </span>
    </>
  );
}

// 自动根据内容类型选择展示的card
export function CardItem({
  file,
  preview,
  remove,
  showActionText,
  fileList,
  itemRenderSzie,
}: ItemRenderProps) {
  const status = file.status ?? 'done';

  let renderItem: ReactNode = null;

  if (status === 'done') {
    // 上传成功
    renderItem = (
      <ImageDoneRender
        itemRenderSzie={itemRenderSzie}
        file={file}
        fileList={fileList}
        preview={preview}
        remove={remove}
        showActionText={showActionText}
      />
    );
  } else if (status === 'uploading') {
    // 上传中
    renderItem = <Progress type="circle" percent={file.percent} size={50} />;
  } else if (status === 'error') {
    // 上传失败
    const rePush =
      typeof file.response === 'function' ? file.response : undefined;

    renderItem = (
      <div style={{ textAlign: 'center' }}>
        <div>上传失败</div>
        <Space size={8}>
          <Button
            type="text"
            size="small"
            onClick={remove}
            style={{ cursor: 'pointer' }}
            icon={<DeleteOutlined />}
          >
            删除
          </Button>
          {rePush ? (
            <Button
              type="text"
              size="small"
              onClick={rePush}
              style={{ cursor: 'pointer' }}
              icon={<RedoOutlined />}
            >
              重试
            </Button>
          ) : null}
        </Space>
      </div>
    );
  }

  return (
    <div className={`ant-upload-list-item ant-upload-list-item_${status}`}>
      {renderItem}
    </div>
  );
}
